require('../../assets/css/index.less')
require('./user-detail.less')
require('../../assets/js/property')
// 引入axios工具
const request = require('../../assets/js/requers')

//服务器地址
const API = 'http://fitness.h5.itsource.cn:3701'

window.onload = () => {

  const nickname = document.querySelector('#nickname')

  //获取用户信息
  function getUserInfo() {
    request.get('/api/user/info').then(res => {
      //1 解构数据
      let {errno, data} = res.data
      //2 判断
      if (errno === 0) {
        //3 处理业务逻辑
        render(data)
      }
    })
  }

  //渲染数据
  function render(data) {
    //图片渲染 服务器地址+相对路径+文件名
    avatar.src = API + data.imgUrl
  }

  //初始化获取用户信息
  getUserInfo()

  //监听file 输入框的change事件
  $('#avatarIpt').addEventListener('change', e => {
    console.log('e :>> ', e.target.files[0])
    //创建FormData 对象 添加文件
    const formData = new FormData()
    formData.append('file', e.target.files[0])
    //发送ajax请求
    request.post('/api/circles/uploadImg', formData).then(res => {
      console.log('res.data :>> ', res.data)
    })
  })

  //获取dom给头像绑定点击事件
  const avatar = document.querySelector('#avatar')
  avatar.addEventListener('click', () => {
    //让上传按钮 触发点击事件
    $('#avatarIpt').click()
  })

  //性别
  const showSexPicker = document.querySelector('#showSexPicker')
  const selSex = document.querySelector('#selSex')
  showSexPicker.addEventListener('click', () => {
    weui.picker(
      [
        {
          label: '男',
          value: 0,
        },
        {
          label: '女',
          value: 1,
        },
      ],
      {
        //确定才选中
        onConfirm: function (result) {
          selSex.textContent = result[0].label
        },
        title: '性别选择',
      }
    )
  })

  //生日选择器
  const showDatePicker = document.querySelector('#showDatePicker')
  let selBirthday = document.querySelector('#selBirthday')
  //监听下拉点击
  showDatePicker.addEventListener('click', () => {
    weui.datePicker({
      start: 1990,
      end: new Date().getFullYear(),
      onConfirm: function (result) {
        console.log(result)
        selBirthday.textContent = result.map(v => String(v.value).padStart(2, '0')).join('-')
      },
      title: '选择生日',
    })
  })

  //省份选择
  const showProvincePicker = document.querySelector('#showProvincePicker')
  let provinces = [] //储存省份
  //获取所有省份
  function getProvinces() {
    request.get('/api/shared/province').then(res => {
      //解构数据
      let {errno, data} = res.data
      //判断
      if (errno === 0) {
        //处理数据
        provinces = data.map(v => {
          return {
            label: v.name,
            value: v.id,
          }
        })
      }
    })
  }
  getProvinces()

  //省份选择器
  const selProvince = document.querySelector('#selProvince')
  showProvincePicker.addEventListener('click', () => {
    weui.picker(provinces, {
      //确定才选中
      onConfirm: function (result) {
        console.log(result)
        selProvince.textContent = result[0].label
      },
      title: '性别选择',
    })
  })
}